﻿using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace HDW_Migrate.Resources;

/// <summary>
/// JWT 工具类
/// </summary>
public static class JWTUtil
{
	/// <summary>
	/// 生成JwtToken
	/// </summary>
	public static string GenerateToken()
    {
        var claims = new Dictionary<string, object>()
        {
            ["jti"] = "DataMigrate",
        };
        var descriptor = new SecurityTokenDescriptor()
        {
            Claims = claims,
            IssuedAt = DateTime.Now,
            Expires = DateTime.Now.AddDays(7),
        };
        var handler = new JwtSecurityTokenHandler();
		
		descriptor.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(KeyFromString("af124f69ddae4cca88316fb6be732059", SecurityAlgorithms.HmacSha256)),
			SecurityAlgorithms.HmacSha256);
	
		var token = handler.CreateToken(descriptor);
		return handler.WriteToken(token);
	}

	
	/// <summary>
	/// 将字符串的key值转换为字节的key（utf8编码）
	/// </summary>
	public static byte[] KeyFromString(string key, string algorithm = null)
	{
		var bytes = Encoding.UTF8.GetBytes(key);

		if (algorithm == SecurityAlgorithms.HmacSha256 && bytes.Length < 32)
		{
			Array.Resize(ref bytes, 32);
			return bytes;
		}

		if (bytes.Length >= 16)
		{	
			return bytes;
		}

		//.net中的hash算法对key有16字节的最小长度要求， 但一些外部算法没有，这里补足长度，以保持key兼容
		Array.Resize(ref bytes, 16);
		return bytes;
	}
}